//
//  PVDPanelNumberViewController.swift
//  ezyform
//
//  Created by MoennigQ on 17/4/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
import AVFoundation
import CoreLocation
import MBProgressHUD
import RxSwift
import RxCocoa

protocol ReloadDataForDeletePanelNumberDelegate: NSObjectProtocol{
    func reloadDataForDeletePanelNumber()
}
class JobDetailPanelsListViewController: BaseViewController {
    fileprivate lazy var disposeBag = DisposeBag()
    let customView = PVDPanelsListView()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.serials("Panel"), subTitle: JobDetailModelHelper.shared.jobDetailModel.gwt_id)
        
        //点击扫描按钮
        self.customView.scanBtn.rx.tap.subscribe { [weak self]_ in
            self?.toAddBarcode(.auto)
        }.disposed(by: self.disposeBag)
        //点击手工增加按钮
        self.customView.addManuallyBtn.rx.tap.subscribe { [weak self]_ in
            self?.toAddBarcode(.manually)
        }.disposed(by: self.disposeBag)
        //spv check result
        self.customView.resultCheckBtn.rx.tap.subscribe { [weak self]_ in
            self?.resultCheckBtnClick()
        }.disposed(by: self.disposeBag)
        //设置左滑动显示编辑删除的action
        self.customView.panelsTableView.rx.setDelegate(self)
            .disposed(by: disposeBag)
        self.customView.modelsDataObserver.accept(JobDetailModelHelper.shared.jobDetailModel.system_detail.panels)
        JobDetailModelHelper.shared.pvd_serial_numbers.onNext(JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers)
        //设置spv UI
        self.customView.setPanelNumberSPVInfo()
        //设置Bottom UI
        self.customView.updateUIByJobStatus()
        //进入panel list获取一次定位信息
        Tool().requestCurrentLocation()
        Tool().getScanLicenseAndRegularExpression()
    }
    //MARK: - 刷新已经上传的spv的验证状态
    func resultCheckBtnClick(){
        if Connectivity.isConnectedToInternet {
            let vm = JobDetailService()
            //set block
            vm.setBlockAfterNetwork({ (result , _) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                
                if let list = JSONDeserializer<PanelNumberImageDBModel>.deserializeModelArrayFrom(json: result as? String) as? Array<PanelNumberImageDBModel> {
                    JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers = list
                    JobDetailModelHelper.shared.jobDetailModel.getLocalPanelNumber()
                    self.customView.setPanelNumberSPVInfo()
                }
            }) { (code, error) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                Tool().showErrorInfo(code, error)
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView()
            vm.getPanelNumberListForSpv()
        }else{
            Tool().showFailureInfo()
        }
        
    }
    //MARK: - 扫描或手动增加barcode
    func toAddBarcode(_ addMode: ScanAddMethodMode){
        // 1
        let status  = CLLocationManager.authorizationStatus()
        
        if JobDetailModelHelper.shared.jobDetailModel.spv_check {
            if status == .denied || status == .restricted {
                Tool().showAlertViewWithTwoBtns(title: R.string.localizable.locationServicesHaveToBeEnabledWhenUsingTheApp(), message: R.string.localizable.turnOnLocationServicesToVerifyRequiredOnsiteDataEgPanelsSerialNumbers(), cancelStr: R.string.localizable.cancel(), confirmStr: R.string.localizable.setting(), yesClosure:  {
                    if  UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!) {
                        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
                    }
                })
            }else{
                self.requestVideoAccess(addMode)
            }
        }else{
            self.requestVideoAccess(addMode)
        }
    }
    private func requestVideoAccess(_ addMode: ScanAddMethodMode){
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.async {
                if status {
                    let vc = ScanBarcodeViewController()
                    vc.scanningType = .panel
                    vc.scanAddMethodMode = addMode
                    vc.modalPresentationStyle = .overFullScreen
                    self.present(vc, animated: true, completion: nil)
                }else{
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
    }
    
    func editPanelNumber(_ index: Int){
        let showPanelList = self.getShowPanelList()
        guard showPanelList.count > index else {return}
        let editPanelCode = showPanelList[index].code
        if let editIndex = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.firstIndex(where: {$0.code == editPanelCode}){//获取在all list中的index
            let editVC = EditBarcodeViewController()
            editVC.scanningType = .panel
            editVC.index = editIndex
            self.navigationController?.pushViewController(editVC, animated: false)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
}
extension JobDetailPanelsListViewController: UITableViewDelegate{
    //MARK: 获取显示的panel list
    private func getShowPanelList()->[PanelNumberImageDBModel]{
        let showPanelList = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.filter({
            if self.customView.filterPanelStatus == .all{
                return true
            }else {
                return $0.spv_status.lowercased() == self.customView.filterPanelStatus.rawValue
            }
        })//界面上可能显示的是invalid或verified的过滤数据，所以必须要哪个目前的
        return showPanelList
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let panelModel = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers[indexPath.row]
        //show image
        if panelModel.image != ""{
            let imagesList: [BrowseImageData] = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.filter({$0.image != ""}).map({BrowseImageData(image: $0.image, code: $0.code, codeType: .Panel)})
            let realIndex = imagesList.firstIndex(where: {$0.image == panelModel.image}) ?? 0
            if imagesList.count > 0 {
                let vc = BrowseImageViewController()
                vc.imagesArray = imagesList
                vc.currentIndex = realIndex
                self.navigationController?.pushViewController(vc,animated: true)
            }
        }

    }
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let spvCheck = JobDetailModelHelper.shared.jobDetailModel.spv_check
        let spvInstalled = JobDetailModelHelper.shared.jobDetailModel.spv_installed
        if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag && (!spvCheck || (spvCheck && !spvInstalled)){
            //edit
            let edit = UIContextualAction(style: .normal, title: nil) { action, view, completionHandler in
                //                var barcode:String!
                self.editPanelNumber(indexPath.row)
                completionHandler(true)
            }
            edit.image = R.image.list_cell_edit_icon()
            edit.backgroundColor = UIColor(hexStr: "#D9D9D9")
            //delete
            let delete = UIContextualAction(style: .normal, title: nil) { action, view, completionHandler in
                self.delOperation(indexPath.row)
                completionHandler(true)
            }
            delete.image = R.image.list_cell_delete_icon()
            delete.backgroundColor = UIColor(hexStr: "#ED3E3E")
            //返回所有的事件按钮
            let configuration = UISwipeActionsConfiguration(actions: [delete, edit])
            return configuration
        }
        return nil

    }
    //Custom Buttons when swipe cell left
    private func delOperation(_ index: Int) {
        let showPanelList = self.getShowPanelList()//界面上可能显示的是invalid或verified的过滤数据，所以必须要哪个目前的
        guard showPanelList.count > index else {return}
        let paneModel = showPanelList[index]//
        let barcode: String  = paneModel.code
        Tool().showAlertViewWithTwoBtns(title: barcode, message: R.string.localizable.areYouSureToDeleteThisSerialNumber("panel"),noClosure: nil) {
            JobDetailModelHelper.shared.jobDetailModel.localDeletedSerialNumbers.append(paneModel)
            //didset通知刷新数据
            if paneModel.operType == "" {//空标识是server数据
                paneModel.removed = 1
                paneModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
                paneModel.operType = DataOperType.Del.rawValue
                //数据库增加删除的本地数据
                DBManager.shared.delSerialNumberData(model: paneModel, tableName: panelnumber_table_name)
                //有网络才能请求删除删除
                if Connectivity.isConnectedToInternet {
                    ModelViewUtil.shared.showLoadingView("Deleting...")
                    UploadManager.shared.uploadOnePanelNumber(paneModel){(succesFlag, code) in
                        ModelViewUtil.shared.hideLoadingView()
                    }
                }
                
            }else{//local data: 新增或修改
                //delete local
                DBManager.shared.deleteLocalPanelInverterByCode(tableName: panelnumber_table_name, code: paneModel.code)
            }
            //1.此代码放在操作数据库后边，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.remove(at: index)
            JobDetailModelHelper.shared.jobDetailModel.broadCastPanelData()
            //设置SPV 信息
            self.customView.setPanelNumberSPVInfo()
        }
    }
    
}
